<?php
/**
 * -----------------------------------------------------
 *
 * models user_model
 *
 * @package     models
 * @subpackage  
 * @category    user_model  -  用户模型类
 * @author      ChenFu
 * @since       2015-6-17 version 1.0
 * -----------------------------------------------------    
 */
class User_model extends CI_Model
{    
	public static $error;
	const TABLE = 'xc_system_users'; // 表名

	public function __construct()
	{
		parent::__construct();
        $this->load->database();
	}

	/**
	 * 增加用户
	 */
	public function insert($data)
	{
		// 查询用户是否存在
		$arr_user = $this->get_username_by_username($data['user_name']);
		if(count($arr_user)!= 0){
			self::$error = 'error';
			return false;
		}
		if($this->db->insert(self::TABLE,$data)){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 根据用户名查询用户名是否存在
	 */
	public function get_username_by_username($username)
	{
		$this->db->where('user_name',$username);
		$query = $this->db->get(self::TABLE);
		return $query->row_array();
	}
             
	/**
	 * 查询所有的用户，并且分页
	 */
	public function get_all_data_and_page($limit)
	{
		$sql = 'select a.*,b.role_name
		from '.self::TABLE.' as a left join xc_system_roles as b
		on a.user_role_id=b.role_id 
		order by a.user_id desc '.$limit;
		
		$query=$this->db->query($sql);
		if($query->num_rows()){
			return $query->result_array();
		}
	}

	/**
	 * 查询共有多少用户
	 */
	public function get_num_rows()
	{
		$query = $this->db->get(self::TABLE);
		return $query->num_rows();
	}

	/**
	 * 编辑用户信息
	 */
	public function update($data,$id)
	{
		if($this->db->update(self::TABLE,$data,'user_id = '.$id)){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 根据id查询用户信息
	 */
	public function get_user_by_userid($user_id)
	{
		$this->db->where('user_id',$user_id);
		$query = $this->db->get(self::TABLE);
		return $query->row_array();
	}

	/**
	 * 根据id删除数据
	 */
	public function delete($id)
	{
		$this->db->where('user_id',$id);
		if($this->db->delete(self::TABLE)){
			return true;
		}else{
			return false;
		}
	}

}